
//
//  BaseAPIManger.m
//  FindJob
//
//  Created by 233 on 16/3/1.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "BaseAPIManger.h"
#import "NetWorkingConfig.h"
#import <AFNetworking.h>
@interface BaseAPIManger ()
@property(nonatomic,strong)NSURLSessionDataTask *dataTask;/**< 用来接收请求的任务 */

@end

@implementation BaseAPIManger
- (void)startRequestURL:(NSString *)urlString parameters:(NSDictionary *)parameter success:(void (^)(id))success failure:(void (^)(NSError *))failure timeout:(NSTimeInterval)timeoutInterval{
    
    // 1. 拼接URL
    NSString *completeURLStr = [NSString stringWithFormat:@"%@%@",kBaseURL,urlString];
    // 2. 封装请求参数
    NSString *jsonStr = [self jsonStringOfDictionary:parameter];
    
    NSDictionary *completeDic = @{@"paramJson":jsonStr};
    // 3. 请行请求
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    // 设置超时时间
    manger.requestSerializer.timeoutInterval = timeoutInterval;
    [manger POST:completeURLStr parameters:completeDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            success(responseObject);
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        NSLog(@"%@",error.localizedDescription);
    }];
}
#pragma mark *** private ***
//字典转json格式
- (NSString *)jsonStringOfDictionary:(NSDictionary *)dict{
    // 1.NSJSONSerialization
    // 2. JSONKit,
    // 3. SBJson
    
   NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options: NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return jsonStr;
}
- (void)cancelRequest{
    [self.dataTask cancel];
}

@end
